//
//  HMMapViewController.m
//  HMMeituanHD
//
//  Created by apple on 2017/5/23.
//  Copyright © 2017年 itheima. All rights reserved.
//

#import "HMMapViewController.h"
#import <MapKit/MapKit.h>
#import "HMBusinessModel.h"
#import "HMCategoryTool.h"
#import "HMHomeNavView.h"
#import "HMCategoryViewController.h"
#import "HMCategoryModel.h"

static NSString *identifier = @"anno";

@interface HMMapViewController ()<DPRequestDelegate, MKMapViewDelegate>
//位置管理者
@property (nonatomic, strong) CLLocationManager *mgr;
//纬度
@property (nonatomic, assign) CGFloat latitude;
//经度
@property (nonatomic, assign) CGFloat longitude;

@property (nonatomic, strong) MKMapView *mapView;
//当前的分类
@property (nonatomic, copy) NSString *currentCategory;

@end

@implementation HMMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //设置地图
    [self setupMapView];
    //设置导航栏
    [self setupNav];
    //监听分类变化通知
    [HMNoteCenter addObserver:self selector:@selector(categoryDidChangeNote:) name:HMCategoryDidChangeNote object:nil];
}

//设置地图
- (void)setupMapView{

    MKMapView *mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    
    [self.view addSubview:mapView];
    self.mgr = [CLLocationManager new];
    //请求授权 info.plist
    [self.mgr requestWhenInUseAuthorization];
    //设置用户跟踪模式
    mapView.userTrackingMode = MKUserTrackingModeFollow;
    //设置代理 监听mapView的移动
    mapView.delegate = self;
    self.mapView = mapView;
}

//设置导航栏
- (void)setupNav{
    
    self.title = @"地图";
    //返回Item
    UIBarButtonItem *backItem = [UIBarButtonItem barBuutonItemWithTarget:self action:@selector(clickBackItem) icon:@"icon_back" highlighticon:@"icon_back_highlighted"];
    
    HMHomeNavView *categoryView = [HMHomeNavView homeNavView];
    //设置数据  利用拉伸优先级设置子标题为空时,让标题占满自定义视图的高度
    categoryView.title = @"全部分类";
    categoryView.subTitle = nil;
    categoryView.iconImgName = @"icon_category_-1";
    categoryView.iconHighligtedImgName = @"icon_category_highlighted_-1";
    
    //监听action事件
    [categoryView addTarget:self action:@selector(clickCategoryItem) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *categoryItem = [[UIBarButtonItem alloc] initWithCustomView:categoryView];
    
    self.navigationItem.leftBarButtonItems = @[backItem, categoryItem];
}

- (void)clickBackItem{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)clickCategoryItem{
    //创建控制器
    HMCategoryViewController *categoryVc = [HMCategoryViewController new];
    
    //设置modal展示样式
    categoryVc.modalPresentationStyle = UIModalPresentationPopover;
    
    //设置来源视图/barButtonItem
    categoryVc.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItems[1];
    //设置Popover的尺寸
    categoryVc.preferredContentSize = CGSizeMake(categoryVc.popoverView.width, categoryVc.popoverView.height);
    //进行modal展示
    [self presentViewController:categoryVc animated:YES completion:nil];
}

#pragma mark - 通知

//分类改变后调用
- (void)categoryDidChangeNote:(NSNotification *)note{
    
    //获取参数
    HMCategoryModel *category = note.userInfo[HMCategoryDidChangeNoteModelKey];
    NSString *subCategory = note.userInfo[HMCategoryDidChangeNoteSubtitleKey];
    //设置导航栏Item
    UIBarButtonItem *item = self.navigationItem.leftBarButtonItems[1];
    HMHomeNavView *categoryView = item.customView;
    categoryView.title = category.name;
    categoryView.subTitle = [subCategory isEqualToString:@"全部"] ? nil : subCategory;
    
    /**
     *  category参数设置规则: 如果有二级分类,则设置为二级分类;如果没有二级分类,则设置一级分类;没有没有一级分类,则不需要设置分类参数
     
     1> 点击"全部分类:   不传参数 category = nil
     2> 点击一级菜单通知:  传递一级名称
     3> 点击二级-"全部"通知: 传递一级名称
     4> 点击二级菜单通知:  传递二级名称
     
     */
    
    //记录当前的分类
    if ([category.name isEqualToString:@"全部分类"]) { //情况1
        
        self.currentCategory = nil;
        
    } else if ((subCategory == nil) || ([subCategory isEqualToString:@"全部"])) { //情况2 & 情况3
        
        self.currentCategory = category.name;
        
    }else {
        
        self.currentCategory = subCategory;
    }

    //删除地图上所有的大头针
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    //请求数据
    [self requestDataFromDPAPI];
}


#pragma mark - MKMapViewDelegate

//区域发生变化后调用
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{

    //记录地图的中心点经纬度
    self.latitude = mapView.region.center.latitude;
    self.longitude = mapView.region.center.longitude;
    
    //进行网络请求
    [self requestDataFromDPAPI];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    //过滤地图定位大头针
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }

    MKAnnotationView *annoV = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if (annoV == nil) {
        annoV = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];

    }
    HMBusinessModel *business = annotation;
    //设置数据  图片需要根据商户的分类到category.plist中查询对应的图片名
    annoV.image = [UIImage imageNamed:[HMCategoryTool categoryImgNameWithCategoryName:business.categories.firstObject]];
    annoV.canShowCallout = YES;
    
    return annoV;
}

#pragma mark - 网络请求

- (void)requestDataFromDPAPI{
    //设置参数
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    //设置经纬度
    [param setValue:@(self.latitude) forKey:@"latitude"];
    [param setValue:@(self.longitude) forKey:@"longitude"];
    //设置限定
    [param setValue:@5 forKey:@"limit"];
    //设置分类
    if (self.currentCategory != nil) {
        
        [param setValue:self.currentCategory forKey:@"category"];
    }
    //请求团购数据
    [[DPAPI new] requestWithURL:@"v1/business/find_businesses" params:param delegate:self];
}



//获取数据成功
- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result{
    
    NSArray *dictArr = result[@"businesses"];
    
    //去掉重复的数据  地图大头针已经的存在的则不需要显示
    NSMutableArray *temp = [NSMutableArray array];
    for (NSDictionary *dict in dictArr) {
        //判断当前地图上是否已经存在
        for (HMBusinessModel *business in self.mapView.annotations) {
            //过滤定位大头针
            if ([business isKindOfClass:[MKUserLocation class]]) {
                //跳出当前这次循环,继续下一个循环
                continue;
            }
            
            if ([dict[@"name"] isEqualToString:business.name]) {
                //已经存在
                [temp addObject:dict];
                break;
            }
        }
    }
    NSMutableArray *newBusinesses = dictArr.mutableCopy;
    [newBusinesses removeObjectsInArray:temp];
    HMLog(@"获取的数据%zd, 去重后的数据%zd", dictArr.count, newBusinesses.count);
    //字典转模型
    NSArray *businesses = [NSArray yy_modelArrayWithClass:[HMBusinessModel class] json:newBusinesses];
    for (HMBusinessModel *business in businesses) {
        //添加大头针模型
        [self.mapView addAnnotation:business];
    }
}


//获取数据失败
- (void)request:(DPRequest *)request didFailWithError:(NSError *)error{
    
    HMLog(@"获取数据失败%@", error);
}


@end
